using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using ViewStateEliminator.Configuration;

namespace ViewStateEliminator.Data
{
    /// <summary>
    /// Provides the ability to save viewstate into a database table. 
    /// Uses EnterpriseLibrary to connect to the database and call stored procedures.
    /// </summary>
    public class ViewStateSQLStorage : IViewstateStorage
    {
        Database _db;
        DbCommand _cmd;
        public ViewStateSQLStorage()
        {
            ViewStateConfiguration config = (ViewStateConfiguration)System.Configuration.ConfigurationManager.GetSection("ViewStateConfiguration");
            if (config.defaultDatabase.Trim().Length == 0)
                _db = DatabaseFactory.CreateDatabase();
            else
                _db = DatabaseFactory.CreateDatabase(System.Configuration.ConfigurationManager.ConnectionStrings[config.defaultDatabase].Name);
        }
        #region IViewstateStorage Members
        public void Add(KeyValuePair<object, string> viewstateItem)
        {
            _cmd = _db.GetStoredProcCommand("ViewStateSource_ADD");
            _db.AddInParameter(_cmd, "viewstateKey", System.Data.DbType.String, viewstateItem.Key.ToString());
            _db.AddInParameter(_cmd, "viewstate", System.Data.DbType.String, viewstateItem.Value.ToString());
            _db.AddInParameter(_cmd, "ip", System.Data.DbType.String, System.Web.HttpContext.Current.Request.UserHostAddress.ToString());

            _db.ExecuteNonQuery(_cmd);
        }
        public KeyValuePair<object, string> Get(object key)
        {
            _cmd = _db.GetStoredProcCommand("ViewStateSource_GET");
            _db.AddInParameter(_cmd, "viewstateKey", System.Data.DbType.String, key.ToString());
            KeyValuePair<object, string> retItem = new KeyValuePair<object, string>(((object)key), ((string)_db.ExecuteScalar(_cmd)));
            return retItem;
        }
        public void Remove(object key)
        {

        }
        #endregion
    }
}
